package com.newflypig.jblog.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.newflypig.jblog.dao.IBaseDAO;
import com.newflypig.jblog.dao.IMenuDAO;
import com.newflypig.jblog.model.BlogCommon;
import com.newflypig.jblog.model.Menu;
import com.newflypig.jblog.service.IMenuService;

@Service("menuService")
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
	
	@Autowired
	private IMenuDAO menuDao;
	
	@Autowired
	private BlogCommon blogCommon;
	
	@Override
	protected IBaseDAO<Menu> getDao() {
		return this.menuDao;
	}

	@Override
	public Menu findByUrlName(String urlName) {
		List<Menu> menus = this.menuDao.findByDC(
			DetachedCriteria.forClass(Menu.class)
				.add(Restrictions.eq("urlName", urlName))
		);
		
		return menus.isEmpty() ? null : menus.get(0);
	}

	@Override
	public List<Menu> findByTitles(String[] menuTitleList) {
		return this.menuDao.findByDC(
			DetachedCriteria.forClass(Menu.class)
			.add(Restrictions.in("title", menuTitleList))
		);
	}

	@Override
	public List<String> findMenuUrls() {
		List<Menu> menusList = this.menuDao.findByDC(
			DetachedCriteria.forClass(Menu.class,"menu")
			.setProjection(Projections.property("menu.urlName").as("urlName"))
			.add(Restrictions.eq("menu.isLeft", true))
			.add(Restrictions.eq("menu.show", true))
			.setResultTransformer(Transformers.aliasToBean(Menu.class))
		);
		
		List<String> urlsList = new ArrayList<String>();
		
		menusList.stream().forEach(menu -> {
			if(!StringUtils.isEmpty(menu.getUrlName()))
				urlsList.add(
					"http://" + this.blogCommon.getBlogUrl() + "/" + menu.getUrlName()
				);
		});
		
		return urlsList;
	}	
}
